﻿using AutoMapper;
using Dto;
using IService;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Model;
using Util;
using WebApi.Filter;

namespace WebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly IUserService _userService;
        private readonly IMapper _mapper;

        public UserController(
            IUserService userService,
            IMapper mapper
            )
        {
            _userService = userService;
            _mapper = mapper;
        }

        [HttpGet("Get")]
        [TypeFilter(typeof(MemoryCacheFilterAttribute))]

        public async Task<ActionResult<ApiResult>> Get(int id)
        {
            var user = await _userService.QueryAsync(id);
            var userDto = _mapper.Map<UserDto>(user);
            return ApiResultHelper.Success(userDto);
        }

        [HttpPost("Create")]
        public async Task<ActionResult<ApiResult>> Create(string name, string userName, string password)
        {
            string pwd = MD5Helper.MD5Encrypt32(password);
            var user = new User
            {
                Name = name,
                UserName = userName,
                Password = pwd
            };
            bool b = await _userService.CreateAsync(user);
            if (!b)
                return ApiResultHelper.Error("插入失败");
            return ApiResultHelper.Success(user);
        }
    }
}
